package com.whu.assignment8.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.whu.assignment8.common.Result;
import com.whu.assignment8.entity.Product;
import com.whu.assignment8.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Aohancool
 * @since 2022-10-17
 */
@RestController
@RequestMapping("/product")
public class productController {

    @Autowired
    private IProductService productService;

    /**
     * 新增或更新商品
     * @param product
     * @return
     */
    @PostMapping
    public Result save(@RequestBody Product product){
        return Result.success(productService.saveOrUpdate(product));
    }

    /**
     * 查询所有商品
     * @return
     */
    @GetMapping
    public Result findAll(){
        System.out.println(productService.list());
        return Result.success(productService.list());
    }


    /**
     * 通过id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id){
//        return Result.success(productService.getById(id));
        QueryWrapper<Product> wrapper=new QueryWrapper<>();
        wrapper.in("id",id);
        return Result.success(productService.getOne(wrapper));
    }

    /**
     * 通过名字查询商品
     * @param name
     * @return
     */
    @GetMapping("/name/{name}")
    public Result findOne(@PathVariable String name){
        QueryWrapper<Product> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",name);
        return Result.success(productService.getOne(queryWrapper));
    }

    /**
     * 通过类型查询商品
     * @param type
     * @return
     */
    @GetMapping("/type/{type}")
    public Result findByType(@PathVariable String type){
        QueryWrapper<Product> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("type",type);
        return Result.success(productService.getOne(queryWrapper));
    }

    /**
     * 删除商品
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        return Result.success(productService.removeById(id));
    }

}
